package com.ncd.form.controller;

import com.alibaba.fastjson.JSONObject;
import com.ncd.common.annotation.Log;
import com.ncd.common.core.controller.BaseController;
import com.ncd.common.core.domain.AjaxResult;
import com.ncd.common.core.page.TableDataInfo;
import com.ncd.common.enums.BusinessType;
import com.ncd.form.domain.Layout;
import com.ncd.form.domain.Record;
import com.ncd.form.result.RecordResult;
import com.ncd.form.service.ILayoutCellService;
import com.ncd.form.service.ILayoutService;
import com.ncd.form.service.IRecordService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/form/record")
public class RecordController extends BaseController
{
    private String prefix = "form/record";

    @Autowired
    private IRecordService recordService;

    @Autowired
    private ILayoutCellService layoutCellService;

    @Autowired
    private ILayoutService layoutService;

    @RequiresPermissions("form:record:view")
    @GetMapping()
    public String record()
    {
        return prefix + "/record";
    }

    /**
     * 查询单记录主列表
     */
    @RequiresPermissions("form:record:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(RecordResult record)
    {
        startPage();
        List<RecordResult> list = recordService.queryList(record);
        return getDataTable(list);
    }


    /**
     * 新增保存单记录主
     */
    @RequiresPermissions("form:record:add")
    @Log(title = "新增表单记录", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestBody JSONObject jsonParam)
    {
        int record=recordService.saveRecord(jsonParam);
        if(record>0){
            return AjaxResult.success(record);
        }else{
            return AjaxResult.error();
        }
    }


    /**
     * 修改保存单记录主
     */
    @RequiresPermissions("form:record:edit")
    @GetMapping("/edit/{recordId}")
    public String editSave(@PathVariable("recordId") Long recordId, ModelMap mmap)
    {
        Record record=recordService.getById(recordId);
        Layout layout=layoutService.getById(record.getLayoutId());
        mmap.put("layout", layout);
        mmap.put("root", layoutCellService.display(record.getRecordVersionId(),recordId));
        return "form/display/layout";
    }

    /**
     * 删除单记录主
     */
    @RequiresPermissions("form:record:remove")
    @Log(title = "表单记录", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(recordService.remove(ids));
    }
}
